﻿using System.Diagnostics;
using System.Reflection;
using Microsoft.Office.Interop.Word;

namespace ResumeSearch
{
    internal class Clprocessor
    {
        /// <summary>
        /// please note that this code is being distributed 
        /// under MIT Liscence by www.ahrcloud.com. We 
        /// encourage attribution of our open source work 
        /// and lab experiements expect the same from you!
        /// </summary>

        private void Freememory()
        {
            Process[] _processarr = Process.GetProcessesByName("WINWORD");

            foreach (Process process in _processarr)
            {
                process.Kill();
            }
        }

        private string Cleanstring(string _stringin)
        {
            string _stringout=string.Empty;

            _stringout = _stringin.Replace(";", "");
            _stringout = _stringout.Replace(":", "");
            _stringout = _stringout.Replace(",", "");
            _stringout = _stringout.Replace("<", "");
            _stringout = _stringout.Replace(">", "");
            _stringout = _stringout.Replace("  ", " ");

            return _stringout;
        }

        public string Convertwordtotext(string docfilepath)
        {
            var mywordapp = new Application();

            object file = docfilepath;

            object nullrefs = Missing.Value;

            Document odoc = mywordapp.Documents.Open(ref file, ref nullrefs, ref nullrefs, ref nullrefs, ref nullrefs,
                                                     ref nullrefs, ref nullrefs, ref nullrefs, ref nullrefs,
                                                     ref nullrefs, ref nullrefs, ref nullrefs);

            Document doc1 = mywordapp.ActiveDocument;

            string _docContent = odoc.Content.Text;

            odoc.Close(ref nullrefs, ref nullrefs, ref nullrefs);

            //clean text partially
            _docContent = Cleanstring(_docContent);

            //clean up resources & memory as currently cannot dispose word properly via api
            Freememory();

            return _docContent;
        }
    }
}